import router, { asyncRoutes } from './router'
import NProgress from 'nprogress' // 进度条
import 'nprogress/nprogress.css' // 进度条样式
import store from './store'

const whiteList = ['/login', '/404']
// 前置守卫
router.beforeEach(async(to, from, next) => {
  // 进度条开启
  NProgress.start()
  // 有token
  if (store.getters.token) {
    if (to.path === '/login') {
      next('/')
      NProgress.done()
    } else {
      if (!store.getters.userId) {
        // 获取用户的权限
        const { roles } = await store.dispatch('user/getUserInfoAsync')
        // console.log(roles)
        // 筛选路由
        const permRoutes = asyncRoutes.filter(item => {
          return roles.menus.includes(item.name)
        })
        // console.log(permRoutes)
        store.commit('user/setRoutes', permRoutes) // 添加动态路由
        // 动态添加路由  404必须在最后
        router.addRoutes([...permRoutes, { path: '*', redirect: '/404', hidden: true }])
        next(to.path)
      } else {
        next()
      }
      next()
    }
  } else { // 没有token
    // 是否存在白名单中
    // indexOf 查找某一项，如果有返回对应下标，没有返回-1
    if (whiteList.indexOf(to.path) >= 0) {
      next()
    } else {
      next('/login')
      NProgress.done()
    }
  }
})

// 后置守卫
router.afterEach(() => {
  // 关闭进度条
  NProgress.done()
})
